package com.example.demo.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class _102_二叉树的层序遍历 {


    public static void main(String[] args) {

        TreeNode root =
                new TreeNode(3,
                        new TreeNode(9, null, null),
                        new TreeNode(20,
                                new TreeNode(15, null, null),
                                new TreeNode(7, null, null)));


        TreeNode root1 = new TreeNode(1, null, null);
        TreeNode root2 = null;
        List<List<Integer>> integers = levelOrder1(root2);
        System.out.println();
    }


    static List<Integer> res = new ArrayList<>();
    static LinkedList<TreeNode> linkedList = new LinkedList<>();

    public static List<Integer> levelOrder(TreeNode root) {
        while (root != null) {
            res.add(root.val);
            if (root.left != null) {
                linkedList.offer(root.left);
            }
            if (root.right != null) {
                linkedList.offer(root.right);
            }
            root = linkedList.poll();
        }
        return res;
    }

    static List<TreeNode> list = new ArrayList<>();
    static List<List<Integer>> result = new ArrayList<>();

    public static List<List<Integer>> levelOrder1(TreeNode root) {
        if(root==null){
            return result;
        }
        list.add(root);
        while (list != null && list.size() > 0) {
            list = test(list);
        }
        return result;
    }

    public static List<TreeNode> test(List<TreeNode> list) {
        List<TreeNode> children = new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                res.add(list.get(i).val);
                if (list.get(i).left != null) {
                    children.add(list.get(i).left);
                }
                if (list.get(i).right != null) {
                    children.add(list.get(i).right);
                }
            }
        }
        result.add(res);
        return children;
    }
}
